package top.shiyiri.transaction;

import org.junit.Test;
import top.shiyiri.bean.User2;
import top.shiyiri.util.JDBCUtils;

import java.lang.reflect.Field;
import java.sql.*;

/**
 * @author Aunean
 * @date 2022/1/19 19:41
 */
/*
1.数据一旦提交，就不可回滚

2.哪些操作会导致数据的自动提交？
    ->DDL操作一旦执行，都会自动提交
        -> set autocommit = false 对 DDL 无效
    ->DML默认情况下，一旦执行，就会自动提交
        ->我们可以通过 set autocommit = false 的方式取消 DML 操作的自动提交
    ->默认在关闭连接时会自动提交数据
 */
public class TransactionTest {

    //通用的增删改操作 --> version 1.0
    public static void update(String sql, Object ... args) {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //1.获取连接
            connection = JDBCUtils.getConnection();
            //2.预编译SQL语句，返回PreparedStatement的实例
            ps = connection.prepareStatement(sql);
            //3.填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1, args[i]);
            }
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.closeResource(connection, ps);
        }
    }

    /*
    针对于数据表 user_table 来说：
    AA 用户 给 BB 用户 转账 100
    */
    @Test
    public void test1() {
        String sql1 = "update user_table set balance = balance - 100 where user = ?";
        update(sql1, "AA");

        //模拟网络异常
        System.out.println(10 / 0);

        String sql2 = "update user_table set balance = balance + 100 where user = ?";
        update(sql2, "BB");
        System.out.println("转账成功");
    }

    //******************************考虑数据库事务后的转账操作******************************
    //通用的增删改操作 --> version 2.0
    public static void update(Connection connection, String sql, Object ... args) {
        PreparedStatement ps = null;
        try {
            //1.预编译SQL语句，返回PreparedStatement的实例
            ps = connection.prepareStatement(sql);
            //2.填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1, args[i]);
            }
            //3.执行
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            JDBCUtils.closeResource(null, ps);
        }
    }

    @Test
    public void test2() {
        Connection connection = null;
        Savepoint savepoint = null;
        try {
            connection = JDBCUtils.getConnection();
            //1.取消数据的自动提交
            connection.setAutoCommit(false);
            savepoint = connection.setSavepoint();//在当前节点保存状态
            String sql1 = "update user_table set balance = balance - 100 where user = ?";
            update(connection, sql1, "AA");

            //模拟网络异常
            System.out.println(10 / 0);

            String sql2 = "update user_table set balance = balance + 100 where user = ?";
            update(connection, sql2, "BB");
            System.out.println("转账成功");
            //2.提交数据
            connection.commit();
        } catch (Exception e) {
            //3.回滚数据
            try {
                connection.rollback(savepoint);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            //修改其为自动提交数据
            //主要针对于使用数据库连接池的使用
            try {
                connection.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JDBCUtils.closeResource(connection, null);
        }
    }

    //通用的查询操作，用于返回数据表中的一条记录（version 2.0，考虑上事务）
    public static <T> T getInstance(Connection conn, Class<T> clazz, String sql, Object ... args) {

        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1, args[i]);
            }
            //执行，获取结果集
            rs = ps.executeQuery();
            //获取结果集的元数据
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();//获取列数
            if (rs.next()) {
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取每个列的列名
                    //String columnName = metaData.getColumnName(i+1);
                    //获取列的别名
                    String columnLabel = metaData.getColumnLabel(i+1);
                    //获取每个列的列值
                    Object columnValue = rs.getObject(i + 1);

                    //通过反射，将对象指定名columnName的属性赋值为指定的值columnValue
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);//保证私有属性也可以访问
                    field.set(t, columnValue);//赋值
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(null, ps, rs);
        }
        return null;
    }

    @Test
    public void testTransactionSelect() throws Exception {
        Connection conn = JDBCUtils.getConnection();
        //设置数据库的隔离级别
        conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        //获取当前连接的隔离级别
        System.out.println(conn.getTransactionIsolation());
        //取消自动提交数据
        conn.setAutoCommit(false);

        String sql = "select user, password, balance from user_table where user = ?";

        User2 user = getInstance(conn, User2.class, sql, "CC");
        System.out.println(user);

    }

    @Test
    public void testTransactionUpdate() throws Exception {
        Connection conn = JDBCUtils.getConnection();
        //取消自动提交数据
        conn.setAutoCommit(false);

        String sql = "update user_table set balance = ? where user = ?";
        update(conn, sql, 3000, "CC");
        System.out.println("已修改");
        Thread.sleep(15000);
        System.out.println("修改结束");
    }
}
